﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;

namespace ColumnModuleAndEdit.ColumnModule
{
	internal class Utility
	{
		public static List<T> GetElements<T>(Document doc) where T : Element
		{
			List<T> list = new List<T>();
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfClass(typeof(T));
			FilteredElementIterator elementIterator = filteredElementCollector.GetElementIterator();
			elementIterator.Reset();
			while (elementIterator.MoveNext())
			{
				Element element = elementIterator.Current;
				T t = element as T;
				if (t != null)
				{
					list.Add(t);
				}
			}
			return list;
		}

		public static T GetElementByName<T>(Document doc, string name) where T : Element
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfClass(typeof(T));
			FilteredElementIterator elementIterator = filteredElementCollector.GetElementIterator();
			elementIterator.Reset();
			while (elementIterator.MoveNext())
			{
				Element element = elementIterator.Current;
				T t = element as T;
				if (t != null && t.Name.CompareTo(name) == 0)
				{
					return t;
				}
			}
			return default(T);
		}

		public static ReferencePlane OffsetCreateRefPlane(Document doc, ReferencePlane host, View pView, XYZ cutVec, XYZ offSet, string name)
		{
			XYZ xyz = new XYZ();
			XYZ xyz2 = new XYZ();
			ReferencePlane result;
			try
			{
				ReferencePlane referencePlane = host;
				if (referencePlane != null)
				{
					xyz = referencePlane.BubbleEnd.Add(offSet);
					xyz2 = referencePlane.FreeEnd.Add(offSet);
					SubTransaction subTransaction = new SubTransaction(doc);
					subTransaction.Start();
					referencePlane = doc.FamilyCreate.NewReferencePlane(xyz, xyz2, cutVec, pView);
					referencePlane.Name = name;
					subTransaction.Commit();
				}
				result = referencePlane;
			}
			catch
			{
				result = null;
			}
			return result;
		}

		public static XYZ GetNormalWithFace(Face face)
		{
            Edge edge = face.EdgeLoops.get_Item(0).get_Item(0);
			UV uv = edge.EvaluateOnFace(0.5, face);
			return face.ComputeNormal(uv);
		}
	}
}
